//
//  MBShortVideoPublishController.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/4/8.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBShortVideoPublishController.h"
#import "MBLocation.h"
#import <ViewDeck.h>
#import "MBBaseTabbarController.h"
#import <FSTextView.h>
#import "MBShortVideoPublishActivityModel.h"
#import "MBShortVideoPublishTagView.h"
#import "MBShortVideoPreviewController.h"
#import "MBQiNiuUpTokenModel.h"
#import "MBSystemFriendController.h"
#import "MBShortVideoPreviewImageController.h"

@interface MBShortVideoPublishController ()
@property(nonatomic, strong)UIButton *rightNavButton;
@property(nonatomic, strong)FSTextView *textView;
@property(nonatomic, strong)UIButton *friendButton;
@property(nonatomic, strong)UIButton *previewButton;
@property(nonatomic, strong)UILabel  *previewTitleLabel;
@property(nonatomic, strong)UIView   *lineView;
@property(nonatomic, strong)MBShortVideoPublishTagView *tagView;
@property(nonatomic, copy) NSString *relevanceFriendIDs;
@end

@implementation MBShortVideoPublishController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self createCustomNav];
    [self layoutChildViews];
    [self sendActivityTagRequest];
    [self setPreViewImage];
}

/**
 获取标签内容
 */
-(void)sendActivityTagRequest {
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_shortvideo_video setParams:@{} isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBShortVideoPublishActivityModel *model = [MBShortVideoPublishActivityModel mj_objectWithKeyValues:AJson];
        weakself.tagView.dataArray = model.labelAlls;
        [weakself refreshUI];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

-(void)refreshUI {
    CGFloat tagViewHeight = [self.tagView getCurrentViewHeight];
    [self.tagView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(tagViewHeight);
    }];
    [self.view layoutIfNeeded];
}

-(void)createCustomNav{
    self.navigationItem.title = @"分享";
    self.view.backgroundColor = Color_White;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightNavButton];
}
-(void)createUI {
    [self.view addSubview:self.textView];
    [self.view addSubview:self.friendButton];
    [self.view addSubview:self.previewButton];
    [self.view addSubview:self.previewTitleLabel];
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.tagView];
}

-(void)layoutChildViews {
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(@100);
    }];
    [self.friendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom).offset(20);
        make.left.equalTo(self.view.mas_left).offset(12);
        make.size.mas_equalTo(CGSizeMake(70, 28));
    }];
    [self.previewButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.friendButton.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(100, 100));
        make.left.mas_equalTo(self.view.mas_left).offset(20);
    }];
    [self.previewTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.previewButton);
        make.height.equalTo(@20);
    }];
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.previewButton.mas_bottom).offset(20);
    }];
    [self.tagView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.lineView.mas_bottom).offset(0);
        make.height.mas_equalTo(135);
    }];
}

#pragma mark - event

-(void)rightNavButtonClick{
    if (![self.textView.text isNotBlank]) {
        [MBProgressHUD  showMessage:@"说点什么吧"];
        return;
    }
    if (self.tagView.selectModel == nil) {
        [MBProgressHUD  showMessage:@"请选择标签"];
        return;
    }
    if (self.publishImage) { /*发布图片*/
        [self uploadImageCoverImage];
    }else {                   /*发布视频*/
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showActivityMessage:@"正在发布.."];
        });
        [self uploadCoverImage];
    }
}

-(void)friendButtonClick:(UIButton *)button {
    MBSystemFriendController *vc = [[MBSystemFriendController alloc]init];
    vc.fromType = MBSystemFriendVCFromTypeShortVideo;
    MB_WeakSelf(self);
    vc.selectIDsBlock = ^(NSString * _Nonnull selectIDs) {
        weakself.relevanceFriendIDs = selectIDs;
    };
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)previewButtonClick:(UIButton *)button {
    if (self.publishImage) {
        MBShortVideoPreviewImageController *vc = [[MBShortVideoPreviewImageController alloc]init];
        vc.previweImage = self.publishImageCoverImage;
        [self.navigationController presentViewController:vc animated:YES completion:nil];
    }else {
        MBShortVideoPreviewController *vc = [[MBShortVideoPreviewController alloc]initWithCoverImage:self.coverImage videoPath:self.videoPath renderMode:RENDER_MODE_FILL_SCREEN showEditButton:NO];
        [self.navigationController presentViewController:vc animated:YES completion:nil];
    }
}

/*发布视频*/
-(void)uploadCoverImage {
    NSDictionary *param = @{};
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kThird_Qiniu_Token setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBQiNiuUpTokenModel *upTokenModel = [MBQiNiuUpTokenModel mj_objectWithKeyValues:AJson];
        QNUploadManager *manager = [[QNUploadManager alloc]init];
        NSData *data = UIImageJPEGRepresentation(self.coverImage, 0.7);
        NSString *timeKey = [NSString stringWithFormat:@"%zd",[[MBTimeManager shateInstance]getCurrentTimestamp]];
        NSString *imageName = [NSString stringWithFormat:@"%@%@%@%@%@",@"upload/image/userId=",filter([MBUserModel sharedMBUserModel].userInfo.userId),@"-",timeKey,@".jpg"];
        [manager putData:data key:imageName token:upTokenModel.upToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.statusCode == 200) {
                NSString *imageURL = [NSString stringWithFormat:@"%@",resp[@"key"]];
                [weakself sendPublishShortVideoRequest:imageURL];
            }
        } option:nil];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

-(void)sendPublishShortVideoRequest:(NSString *)coverImageURL {
    NSMutableDictionary *param  = [NSMutableDictionary dictionary];
    [param setValue:filter([MBUserModel sharedMBUserModel].userInfo.userId) forKey:@"userId"];
    [param setValue:@(self.coverImage.size.width) forKey:@"wide"];
    [param setValue:@(self.coverImage.size.height) forKey:@"high"];
    [param setValue:@"1" forKey:@"type"];
//    [param setValue:@"1" forKey:@"type2"];
    [param setValue:coverImageURL forKey:@"coverUrl"];
    [param setValue:self.tagView.selectModel.labelName forKey:@"videoLabel"];
    [param setValue:filter(self.videoURL) forKey:@"videoUrl"];
    [param setValue:self.textView.text forKey:@"videoHeadline"];
    [param setValue:filter(self.videoDownloadURL) forKey:@"downloadUrl"];
    if ([self.relevanceFriendIDs isNotBlank]) {
        [param setValue:self.relevanceFriendIDs forKey:@"relevanceUser"];
    }
    switch (self.entityType) {
        case MBShortVideoEntityTypeNormal:[param setValue:@"1" forKey:@"type2"];break;
        case MBShortVideoEntityTypeIdle:[param setValue:@"2" forKey:@"type2"]; break;
        case MBShortVideoEntityTypeActivity:[param setValue:@"3" forKey:@"type2"]; break;

        default:[param setValue:@"2" forKey:@"type2"]; break;
    }
    if ([MBLocation shareMBLocation].city.length > 0) {
        [param setValue:[MBLocation shareMBLocation].province forKey:@"province"];
        [param setValue:[MBLocation shareMBLocation].city forKey:@"city"];
        [param setValue:[MBLocation shareMBLocation].district forKey:@"district"];
        [param setValue:[MBLocation shareMBLocation].lastName forKey:@"address"];
        [param setValue:@([MBLocation shareMBLocation].longitude) forKey:@"longitude"];
        [param setValue:@([MBLocation shareMBLocation].latitude) forKey:@"latitude"];
    }
    MB_WeakSelf(self);
    
    [MBHttpRequset requestWithUrl:kLive_shortVideo_publish setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD  showMessage:@"发布成功"];
        MBBaseTabbarController *tabVC = (MBBaseTabbarController *)weakself.viewDeckController.centerViewController;
        [weakself.navigationController popToRootViewControllerAnimated:NO];
        switch (self.entityType) {
            case MBShortVideoEntityTypeNormal:   [tabVC updateCurrentIndex:0]; break;
            case MBShortVideoEntityTypeIdle:        [tabVC updateCurrentIndex:3]; break;
            case MBShortVideoEntityTypeActivity:        [tabVC updateCurrentIndex:1]; break;

            default:[tabVC setSelectedIndex:0]; break;
        }
    } failure:^(id  _Nonnull AJson) {
        [MBProgressHUD  showMessage:@"发布失败"];
         [MBProgressHUD hideHUD];
    }];
}

-(void)setPreViewImage {
    if (self.publishImage) {
        [self.previewButton setBackgroundImage:self.publishImageCoverImage forState:UIControlStateNormal];
    }else {
        [self.previewButton setBackgroundImage:self.coverImage forState:UIControlStateNormal];
    }
}

#pragma mark - 发布图片
-(void)uploadImageCoverImage {
    NSDictionary *param = @{};
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kThird_Qiniu_Token setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBQiNiuUpTokenModel *upTokenModel = [MBQiNiuUpTokenModel mj_objectWithKeyValues:AJson];
        QNUploadManager *manager = [[QNUploadManager alloc]init];
        NSData *data = UIImageJPEGRepresentation(self.publishImageCoverImage, 0.7);
        NSString *timeKey = [NSString stringWithFormat:@"%zd",[[MBTimeManager shateInstance]getCurrentTimestamp]];
        NSString *imageName = [NSString stringWithFormat:@"%@%@%@%@%@",@"upload/image/userId=",filter([MBUserModel sharedMBUserModel].userInfo.userId),@"-",timeKey,@".jpg"];
        [manager putData:data key:imageName token:upTokenModel.upToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.statusCode == 200) {
                NSString *imageURL = [NSString stringWithFormat:@"%@",resp[@"key"]];
                [weakself uploadPublishImage:imageURL];
            }
        } option:nil];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
/*上传需要发布的长图片*/
-(void)uploadPublishImage:(NSString *)coverImage {
    NSDictionary *param = @{};
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kThird_Qiniu_Token setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBQiNiuUpTokenModel *upTokenModel = [MBQiNiuUpTokenModel mj_objectWithKeyValues:AJson];
        QNUploadManager *manager = [[QNUploadManager alloc]init];
        NSData *data = UIImageJPEGRepresentation(self.publishImage, 0.7);
        NSString *timeKey = [NSString stringWithFormat:@"%zd",[[MBTimeManager shateInstance]getCurrentTimestamp]];
        NSString *imageName = [NSString stringWithFormat:@"%@%@%@%@%@",@"upload/image/userId=",filter([MBUserModel sharedMBUserModel].userInfo.userId),@"-",timeKey,@".jpg"];
        [manager putData:data key:imageName token:upTokenModel.upToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.statusCode == 200) {
                NSString *imageURL = [NSString stringWithFormat:@"%@",resp[@"key"]];
                [weakself sendPublishImageRequest:coverImage publishImage:imageURL];
            }
        } option:nil];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

-(void)sendPublishImageRequest:(NSString *)coverImageURL publishImage:(NSString *)publishImage{
    NSMutableDictionary *param  = [NSMutableDictionary dictionary];
    [param setValue:filter([MBUserModel sharedMBUserModel].userInfo.userId) forKey:@"userId"];
    [param setValue:@(self.publishImageCoverImage.size.width) forKey:@"wide"];
    [param setValue:@(self.publishImageCoverImage.size.height) forKey:@"high"];
    [param setValue:@"2" forKey:@"type"];
//    [param setValue:@"2" forKey:@"type2"];
    [param setValue:coverImageURL forKey:@"coverUrl"];
    [param setValue:self.tagView.selectModel.labelName forKey:@"videoLabel"];
    [param setValue:publishImage forKey:@"videoUrl"];
    [param setValue:self.textView.text forKey:@"videoHeadline"];
    [param setValue:publishImage forKey:@"downloadUrl"];
    if ([self.relevanceFriendIDs isNotBlank]) {
        [param setValue:self.relevanceFriendIDs forKey:@"relevanceUser"];
    }
    if ([MBLocation shareMBLocation].city.length > 0) {
        [param setValue:[MBLocation shareMBLocation].province forKey:@"province"];
        [param setValue:[MBLocation shareMBLocation].city forKey:@"city"];
        [param setValue:[MBLocation shareMBLocation].district forKey:@"district"];
        [param setValue:[MBLocation shareMBLocation].lastName forKey:@"address"];
        [param setValue:@([MBLocation shareMBLocation].longitude) forKey:@"longitude"];
        [param setValue:@([MBLocation shareMBLocation].latitude) forKey:@"latitude"];
    }
    switch (self.entityType) {
        case MBShortVideoEntityTypeNormal:[param setValue:@"1" forKey:@"type2"];break;
        case MBShortVideoEntityTypeIdle:[param setValue:@"2" forKey:@"type2"]; break;
        case MBShortVideoEntityTypeActivity:[param setValue:@"3" forKey:@"type2"]; break;
        default:[param setValue:@"2" forKey:@"type2"]; break;
            
    }
    MB_WeakSelf(self);
    
    [MBHttpRequset requestWithUrl:kLive_shortVideo_publish setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        [MBProgressHUD  showMessage:@"分享成功"];
        MBBaseTabbarController *tabVC = (MBBaseTabbarController *)weakself.viewDeckController.centerViewController;
        [weakself.navigationController popToRootViewControllerAnimated:NO];
        switch (self.entityType) {
            case MBShortVideoEntityTypeNormal:        [tabVC updateCurrentIndex:0]; break;
            case MBShortVideoEntityTypeIdle:        [tabVC updateCurrentIndex:3]; break;
            case MBShortVideoEntityTypeActivity:        [tabVC updateCurrentIndex:1]; break;

            default:[tabVC setSelectedIndex:0]; break;
        }
    } failure:^(id  _Nonnull AJson) {
        
    }];
}



#pragma mark - getter
-(UIButton *)rightNavButton {
    if (_rightNavButton == nil) {
        _rightNavButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightNavButton setTitle:@"发布" forState:UIControlStateNormal];
        [_rightNavButton setTitleColor:Color_FF8000 forState:UIControlStateNormal];
        _rightNavButton.titleLabel.font = kFont(16);
        [_rightNavButton addTarget:self action:@selector(rightNavButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightNavButton;
}
-(FSTextView *)textView {
    if (_textView == nil) {
        _textView = [FSTextView textView];
        _textView.placeholder = @"说点什么";
        _textView.placeholderFont = kFont(14);
        _textView.placeholderColor = Color_AAAAAA;
    }
    return _textView;
}
-(UIButton *)friendButton {
    if (_friendButton == nil) {
        _friendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_friendButton setTitle:@"@好友" forState:UIControlStateNormal];
        [_friendButton setTitleColor:Color_666666 forState:UIControlStateNormal];
        _friendButton.titleLabel.font = kFont(14);
        _friendButton.layer.cornerRadius = 14.0;
        _friendButton.layer.masksToBounds = YES;
        _friendButton.layer.borderColor = Color_666666.CGColor;
        _friendButton.layer.borderWidth = 0.5;
        [_friendButton addTarget:self action:@selector(friendButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _friendButton;
}

-(UIButton *)previewButton {
    if (_previewButton == nil) {
        _previewButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_previewButton addTarget:self action:@selector(previewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _previewButton;
}
-(UILabel *)previewTitleLabel {
    if (_previewTitleLabel == nil) {
        _previewTitleLabel = [[UILabel alloc]init];
        _previewTitleLabel.text = @"预览";
        _previewTitleLabel.textColor = Color_White;
        _previewTitleLabel.font = kFont(12);
        _previewTitleLabel.textAlignment = NSTextAlignmentCenter;
        _previewTitleLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }
    return _previewTitleLabel;
}
-(UIView *)lineView {
    if (_lineView == nil) {
        _lineView = [[UIView alloc]init];
        _lineView.backgroundColor = Color_Line;
    }
    return _lineView;
}
-(MBShortVideoPublishTagView *)tagView {
    if (_tagView == nil) {
        _tagView = [MBShortVideoPublishTagView nibView];
    }
    return _tagView;
}
@end
